package cn.chinaflame.pagodas.utils.stl;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import java.io.IOException;
import java.nio.charset.Charset;

public class HttpClientUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

    public static String sendPost(String url, String param) throws IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(6000).
                setSocketTimeout(60000).setConnectionRequestTimeout(3000).build();
        post.setConfig(requestConfig);
        //构建消息实体
        StringEntity entity = new StringEntity(param, Charset.forName("UTF-8"));
        entity.setContentEncoding("UTF-8");
        // 发送Json格式的数据请求
        entity.setContentType("application/json");
        post.setEntity(entity);
        CloseableHttpResponse response = client.execute(post);
        HttpEntity responseEntity = response.getEntity();
        String result = null;
        if (responseEntity != null) {
            result = EntityUtils.toString(responseEntity, "utf-8");
        }
        EntityUtils.consume(responseEntity);
        logger.info("sendPost;END;param:{}", JSON.toJSONString(param));
        return result;
    }

}
